#include "PortHandler.h"
#include <QApplication>
#include "../Common/led.h"

PortHandler::PortHandler() : QObject(),
    startByte(100)
{
	port = new QSerialPort();
}

PortHandler::~PortHandler()
{
	delete port;
}

void PortHandler::close(){
	portState = Close;
}

bool PortHandler::open(QString portName)
{
	portState = Close;
	connect(port,SIGNAL(openPortFailed()),this,SLOT(onPortFail()));
	connect(port,SIGNAL(openPortSuccess()),this,SLOT(onPortOK()));
	port->usePort(&portName, Baud115200, CS8, SB1, ParityNone);
	port->start();

	for(int i=0;i<10;i++){
		if(portState != Close) break;
		QApplication::processEvents();
		MyThread::msleep(100);
	}

    return portState==Open ? true : false;
}

void PortHandler::onPortOK(){
    portState = Open;
}

void PortHandler::onPortFail(){
    portState = OpenError;
}

void PortHandler::sendData(){
	if(colorBuffer.size()==0) return;
	port->writeBuffer(&colorBuffer);
}

void PortHandler::setLeds(QList<Led *> &list){
	colorBuffer.clear();
    colorBuffer.append(startByte);
	for(int i=0; i<list.size(); i++){
		QColor col = list.at(i)->getColor();
        if(col.red()==startByte) col.setRed(startByte+1);
        if(col.green()==startByte) col.setGreen(startByte+1);
        if(col.blue()==startByte) col.setBlue(startByte+1);
		colorBuffer.append((char)col.red());
		colorBuffer.append((char)col.green());
		colorBuffer.append((char)col.blue());
	}
}
